package com.share.auth.service;

import com.share.common.core.constant.SecurityConstants;
import com.share.common.core.domain.R;
import com.share.common.core.exception.ServiceException;
import com.share.common.core.utils.StringUtils;
import com.share.common.core.utils.ip.IpUtils;
import com.share.system.api.model.LoginUser;
import com.share.user.api.RemoteUserService;
import com.share.user.api.domain.UpdateUserLogin;
import com.share.user.api.domain.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author YC
 */
@Component
public class H5LoginService {

    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * 登录的方法
     *
     * @param code 微信登录临时code
     * @return LoginUser
     */
    public LoginUser login(String code) {
        // 判断code是否为空
        if (StringUtils.isEmpty(code)) {
            throw new ServiceException("微信code为空");
        }
        // 远程调用完成登录，返回userInfo
        R<UserInfo> userInfoR = remoteUserService.wxLogin(code);
        UserInfo userInfo = userInfoR.getData();
        // 判断返回userInfo是否为空
        if (userInfo == null) {
            throw new ServiceException("用户信息不存在");
        }
        String status = userInfo.getStatus();
        if ("2".equals(status)) {
            throw new ServiceException("账号被禁用");
        }
        // 封装数据到LoginUser对象里面
        LoginUser loginUser = new LoginUser();
        loginUser.setUserid(userInfo.getId());
        loginUser.setUsername(userInfo.getWxOpenId());
        loginUser.setStatus(userInfo.getStatus() + "");
//        // 记录当前的登录信息
//        UpdateUserLogin updateUserLogin = new UpdateUserLogin();
//        updateUserLogin.setUserId(userInfo.getId());
//        updateUserLogin.setLastLoginIp(IpUtils.getIpAddr());
//        updateUserLogin.setLastLoginTime(new Date());
//        remoteUserService.updateUserLogin(updateUserLogin, SecurityConstants.INNER);
        return loginUser;
    }
}
